package com.codefish.codefishseckill.config.interceptor;

import com.codefish.codefishseckill.entity.User;
import com.codefish.codefishseckill.exception.GlobalException;
import com.codefish.codefishseckill.sentinel.CurrentLimitAccessService;
import com.codefish.codefishseckill.vo.RespBeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器，接口限流
 *
 * @author codefish
 * @version 1.0
 * @date 2022/08/05 下午 02:39
 */
@Component
public class LimitAccessInterceptor implements HandlerInterceptor {
    @Autowired
    CurrentLimitAccessService currentLimitAccessService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        User user = (User) request.getSession().getAttribute("userInfo");
        boolean canAccessURI = currentLimitAccessService.canAccessURI(request, user);
        if (canAccessURI) {
            return true;
        } else {
            throw new GlobalException(RespBeanFactory.denied("点击过于频繁，请稍后再试!"));
        }
    }
}
